package com.iscas.green.extralindextest.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * 计时器服务，可以持续输出当前时间
 */
@Service
public class TimerService {

    private static final Logger log = LoggerFactory.getLogger(TimerService.class);
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
    private ScheduledExecutorService executor;
    private ScheduledFuture<?> timerTask;
    private boolean running = false;
    
    /**
     * 启动计时器，每秒输出一次当前时间，持续指定的分钟数
     * 
     * @param durationMinutes 持续时间（分钟）
     * @return 启动结果消息
     */
    public String startTimer(int durationMinutes) {
        if (running) {
            log.info("计时器已经在运行中");
            return "计时器已经在运行中";
        }
        
        if (durationMinutes <= 0) {
            durationMinutes = 5; // 默认5分钟
        } else if (durationMinutes > 30) {
            durationMinutes = 30; // 最大30分钟
        }
        
        final int finalDuration = durationMinutes;
        log.info("启动计时器，持续时间: {} 分钟", finalDuration);
        
        executor = Executors.newScheduledThreadPool(1);
        
        // 计算总次数（每秒一次，持续分钟数*60）
        final int totalTicks = finalDuration * 60;
        final int[] tickCount = {0};
        
        timerTask = executor.scheduleAtFixedRate(() -> {
            tickCount[0]++;
            LocalDateTime now = LocalDateTime.now();
            log.info("当前时间: {}", now.format(formatter));
            
            if (tickCount[0] >= totalTicks) {
                log.info("计时器结束，已运行 {} 分钟", finalDuration);
                stopTimer();
            }
        }, 0, 1, TimeUnit.SECONDS);
        
        running = true;
        return "计时器已启动，将持续 " + finalDuration + " 分钟";
    }
    
    /**
     * 停止计时器
     * 
     * @return 停止结果消息
     */
    public String stopTimer() {
        if (!running) {
            log.info("计时器未运行");
            return "计时器未运行";
        }
        
        if (timerTask != null) {
            timerTask.cancel(false);
        }
        
        if (executor != null) {
            executor.shutdown();
            try {
                if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
                    executor.shutdownNow();
                }
            } catch (InterruptedException e) {
                executor.shutdownNow();
                Thread.currentThread().interrupt();
                log.error("停止计时器时被中断", e);
            }
        }
        
        running = false;
        log.info("计时器已停止");
        return "计时器已停止";
    }
} 